package com.boot.springboot.controller;

import com.boot.springboot.pojo.ResponseMessage;
import com.boot.springboot.pojo.User;
import com.boot.springboot.pojo.dto.UserDto;
import com.boot.springboot.service.IUserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //接口方法返回对象，装换成json文本
@RequestMapping("/user") //localhost:8080/user/**
public class UserController {
    @Autowired //自动装配
    IUserService userService;
//通过Rest在http协议中实现

    //增加
    @PostMapping //前端请求地址localhost:8080/user method:post
    public ResponseMessage<User> add(@Validated @RequestBody UserDto user){
        User userNew=userService.add(user);
        return ResponseMessage.success(userNew);
    }
    //查询
    @GetMapping("/{userId}")
    public ResponseMessage<User> get(@PathVariable Integer userId){
        User userNew=userService.get(userId);
        return ResponseMessage.success(userNew);
    }


    //修改
    @PutMapping
    public ResponseMessage<User> edit(@Validated @RequestBody UserDto user){
        User userNew=userService.edit(user);
        return ResponseMessage.success(userNew);
    }

    //删除用户
    @DeleteMapping("/{userId}")
    public ResponseMessage<User> delete(@PathVariable Integer userId){
       userService.delete(userId);
       return ResponseMessage.delete();
    }
    //查询所有数据
    @GetMapping
    public ResponseMessage<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseMessage.success(users);
    }
}
